package com.gateway.security;

import com.gateway.common.dto.RuleData;
import com.gateway.common.dto.SelectorData;
import com.gateway.common.enums.AuthenticationTypeEnum;
import com.gateway.common.enums.PluginEnum;
import com.gateway.plugin.api.GatewayPlugin;
import com.gateway.plugin.api.GatewayPluginChain;
import com.gateway.plugin.base.AbstractGatewayPlugin;
import com.gateway.security.common.authentication.client.ClientAuthenticationToken;
import com.gateway.security.common.extract.ClientExtractor;
import com.gateway.security.common.extract.DefaultClientExtractor;
import com.gateway.security.common.token.SecurityToken;
import com.gateway.security.extract.ClientExtractorFactory;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.Objects;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/12 11:02
 **/
public class SecurityGatewayFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return exchange.getPrincipal()
                .filter(ClientAuthenticationToken.class::isInstance)
                .cast(ClientAuthenticationToken.class)
                .flatMap(token -> chain.filter(ClientExtractorFactory.extract(token.getApiDefinition().getAuthenticationType().getType(), exchange, token)))
                .switchIfEmpty(chain.filter(exchange));
    }
}
